import PropTypes from "prop-types";

class CountA extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  add() {
    this.setState((state) => ({
      count: state.count + 1,
    }));
  }
  render() {
    const { count } = this.state;
    return (
      <div>
        <h2>{count}</h2>
        <button onClick={this.add.bind(this)}>点击自增</button>
      </div>
    );
  }
}

const CountB = (props) => {
  const [count, setCount] = React.useState(0);
  return (
    <div>
      <h2>{count} </h2>
      <button onClick={() => setCount(count + 1)}>自增</button>
    </div>
  );
};

const ChildA = (props) => {
  console.log("---child a props", props);
  let { name, render, list } = props; //解构
  return (
    <div>
      <h1>我是childA{name}</h1>
      {render(list)}
    </div>
  );
};

const ChildB = (props) => {
  console.log("---child b props", props);
  return (
    <div>
      <h1>我是childB</h1>
    </div>
  );
};

const ChildC = (props) => {
  console.log("---child c props", props);
  return (
    <div>
      <h2>我是childC</h2>
    </div>
  );
};

//配合prop-types 实现类型和必填校验
ChildC.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number.isRequired,
  onEat: PropTypes.func,
  footer: PropTypes.element,
  header: PropTypes.node,
  height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  gender: PropTypes.oneOf(["男", "女"]),
};
//给非必填的props添加默认值
ChildC.defaultProps = {
  name: "ace",
};

export default class extends React.Component {
  handler() {
    console.log("--handler");
  }

  render() {
    return (
      <div>
        <h2>我是props</h2>
        <CountA></CountA>
        {/* 组件A实现点击自增功能 */}
        <CountB />
        <hr />
        <ChildA
          name="张三"
          age={18}
          show={false}
          a={null}
          b={undefined}
          info={{ a: 1, b: 2 }}
          list={[1, 2, 3, 4]}
          c={Math.random()}
          onRun={this.handler}
          foot={<footer>我是底部</footer>}
          render={(list) => (
            <ul>
              {list.map((ele) => (
                <li key={ele}>{ele}</li>
              ))}
            </ul>
          )}
        ></ChildA>
        <hr />
        <ChildB>
          <div>你好</div>
          <div>世界</div>
          {"Hello World"}
        </ChildB>
        <ChildB>{() => <div>Hello World</div>} </ChildB>
        <hr />
        <ChildC
          name={"李四"}
          age={19}
          footer={<div></div>}
          header={1000}
          height={100}
          gender="男"
        ></ChildC>
      </div>
    );
  }
}
